/*
 * @Description: 档案征集整体结构
 * @Author: Zzt
 * @Date: 2022-12-28 11:22:27
 * @LastEditTime: 2023-01-19 16:51:57
 */

import { useEffect, useMemo, useState } from 'react';
import { Button } from 'antd';
import { isNullObj } from '@/utils';
import { IFetchArchivesByPageParams } from '@/api/archives/archives';
import CommonTableWrap from '../CommonTableWrap';
import EditReceiveAndSendItem from '../dialogs/EditReceiveAndSendItem';
import DetailReceiveAndSendItem from '../dialogs/DetailReceiveAndSendItem';
import RecordOperates from './RecordOperates';
import { EnumInitRepoName } from '@/view/system/LIBManage/dictionaries';
import type { IPageQuery } from '@/interfaces/global';
import { useReceiveAndSendCollectionContext } from '../../contexts/ReceiveAndSendCollectionContext';

interface IRecordLevelProps {
  selectChange: any;
}

const RecordLevel = (props: IRecordLevelProps) => {
  const { selectChange } = props;
  const { selectAT, recordsData, getTopLevelList } = useReceiveAndSendCollectionContext();

  const [selectItems, setSelectItems] = useState<number[]>([]);
  // 表格加载
  const [loading, setLoading] = useState(false);
  // 总条目数
  const [total, setTotal] = useState(0);
  // 表格请求参数
  const [listQuery, setListQuery] = useState<IPageQuery<IFetchArchivesByPageParams>>({
    pageNo: 1,
    pageSize: 10,
    param: null
  });
  // 编辑弹窗状态
  const [editDialogVisible, setEditDialogVisible] = useState(false);
  // 详情弹窗状态
  const [detailDialogVisible, setDetailDialogVisible] = useState(false);
  // 编辑弹窗数据
  const [editData, setEditData] = useState({});

  useEffect(() => {
    if (selectAT?.atCode) {
      setListQuery((state: any) => {
        return {
          ...state,
          param: {
            commonParams: {
              // TODO dbName需要获取
              dbName: EnumInitRepoName.Collection
            },
            atCode: selectAT.atCode,
            atType: selectAT.atType,
            level: selectAT.atLevel
          }
        };
      });
    }
  }, [selectAT]);

  useEffect(() => {
    if (listQuery?.param && !isNullObj(listQuery.param)) {
      setLoading(true);
      getTopLevelList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 选中条目方法
   * @param {number} record 页码
   */
  const onSelectChange = (record: any) => {
    selectChange(recordsData.downLevel, record, recordsData.fieldList);
  };

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description: 打开编辑弹窗方法
   * @param {any} data 编辑的内容
   */
  const showEditDialog = (data: any) => {
    setEditData(data);
    setEditDialogVisible(true);
  };

  /**
   * @description: 打开详情弹窗方法
   * @param {any} data 编辑的内容
   */
  const showDetailDialog = (data: any) => {
    setEditData(data);
    setDetailDialogVisible(true);
  };

  // 表格操作列
  const actions = (record: any) => [
    <Button
      type="link"
      onClick={(evt) => {
        evt.stopPropagation();
        showEditDialog(record);
      }}
    >
      编辑
    </Button>,
    <Button
      type="link"
      onClick={(evt) => {
        evt.stopPropagation();
        showDetailDialog(record);
      }}
    >
      详情
    </Button>
  ];

  return (
    <>
      <CommonTableWrap
        title="资料管理"
        list={recordsData?.data || []}
        fieldList={recordsData?.fields || []}
        selectItems={selectItems}
        loading={loading}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          showTotal: (total) => `共 ${total} 条`,
          onChange: pageChange
        }}
        operates={<RecordOperates selectItems={selectItems} />}
        actions={actions}
        setSelectedItem={setSelectItems}
        selectChange={onSelectChange}
      />

      {/* 编辑弹窗 */}
      {useMemo(
        () => (
          <EditReceiveAndSendItem
            visible={editDialogVisible}
            coordinate={{
              atCode: selectAT.atCode,
              atType: selectAT.atType,
              level: selectAT.atLevel
            }}
            data={editData}
            onClose={() => {
              setEditDialogVisible(false);
            }}
          />
        ),
        [editDialogVisible]
      )}

      {/* 详情弹窗 */}
      {useMemo(
        () => (
          <DetailReceiveAndSendItem
            visible={detailDialogVisible}
            data={editData}
            onClose={() => {
              setDetailDialogVisible(false);
            }}
          />
        ),
        [detailDialogVisible]
      )}
    </>
  );
};

export default RecordLevel;
